package com.cjst.controller.subject;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cjst.controller.base.BaseController;
import com.cjst.pojo.subject.QuestClass;
import com.cjst.pojo.subject.QuestClassHistory;
import com.cjst.pojo.subject.Subjects;
import com.cjst.pojo.subject.SubjectsHistory;
import com.cjst.pojo.sys.SysUser;
import com.cjst.service.subject.QuestClassHistoryService;
import com.cjst.service.subject.QuestClassService;
import com.cjst.service.subject.SubjectsHistoryService;
import com.cjst.service.subject.SubjectsService;
import com.cjst.service.sys.SysUserService;
import com.cjst.sql.C;
import com.cjst.sql.Method;
import com.cjst.sql.WherePrams;
import com.cjst.util.UserPrincipalUtil;
import com.cjst.util.code.PageUtil;
import com.cjst.util.common.DateUtil;
import com.cjst.util.json.ResultObj;
@Controller
@RequestMapping("questClass")
public class QuestClassController  extends BaseController{
	protected final Logger log = Logger.getLogger(QuestClassController.class);
	@Autowired
	private QuestClassService questClassService;
	
	@Autowired
	private SubjectsService subjectsService;
	
	
	@Autowired
	private QuestClassHistoryService questClassHistoryService;
	
	@Autowired
	private SubjectsHistoryService subjectsHistoryService;
	
	@Autowired
	private SysUserService sysUserService;
	@RequestMapping("")
	private String toquestClass(Model model){
		/*SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
		WherePrams cwheres=Method.where("delFlag", C.EQ, 0);
		UserPrincipalUtil.getPriceMegod(cwheres, sysUser, "userId");
		cwheres.orderBy(" create_time desc ");
		List<SchoolCourse> courseList=schoolCourseService.list(cwheres);
		model.addAttribute("courseList", courseList);*/
		return "subjects/questClass/questClass";
	}
	
	@RequestMapping("/toResult")
	private String toResult(Model model){
		/*SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
		WherePrams cwheres=Method.where("delFlag", C.EQ, 0);
		UserPrincipalUtil.getPriceMegod(cwheres, sysUser, "userId");
		cwheres.orderBy(" create_time desc ");
		List<SchoolCourse> courseList=schoolCourseService.list(cwheres);
		model.addAttribute("courseList", courseList);*/
		return "subjects/questClass/questClass";
	}
	
	@RequestMapping(value = "/list")
	@ResponseBody
	public Object list(String courseName,String className) {
		SysUser sysUsers = (SysUser) SecurityUtils.getSubject().getPrincipal();
		WherePrams wheres=Method.where("isDelete", C.EQ, 0);
		if(className!=null && className.length()>0){
			wheres.and("className", C.LIKE, className);
		}
		if(courseName!=null && courseName.length()>0){
			//wheres.and("courseId", C.EQ, courseName);						//
			wheres.casual(" AND EXISTS(select id from t_school_course a where a.id=t_quest_class.target and a.course_name like '%"+courseName+"%')");
		}
		UserPrincipalUtil.getPriceMegod(wheres, sysUsers, "createUser");
		wheres.orderBy(" create_time desc ");
		PageUtil<QuestClass> page=questClassService.listPageCount(wheres);
		if(page!=null){
			List<QuestClass> subjectsList=page.getData();
			if(subjectsList!=null && subjectsList.size()>0){
				for (QuestClass questClass : subjectsList) {
					String userId=questClass.getCreateUser();
					String rcourseId=questClass.getTarget();
					if(userId!=null && userId.length()>0){
						SysUser sysUser=sysUserService.get(userId);
						if(sysUser!=null){
							questClass.setCreateUser(sysUser.getName());;
						}
					}
				}
			}
		}
		return super.packForBT(page);
	}
	
	@RequestMapping(value = "/listResult")
	@ResponseBody
	public Object listResult(String courseName,String className) {
		SysUser sysUsers = (SysUser) SecurityUtils.getSubject().getPrincipal();
		WherePrams wheres=Method.where("isDelete", C.EQ, 0);
		if(className!=null && className.length()>0){
			wheres.and("className", C.LIKE, className);
		}
		if(courseName!=null && courseName.length()>0){
			//wheres.and("courseId", C.EQ, courseName);						//
			wheres.casual(" AND EXISTS(select id from t_school_course a where a.id=t_quest_class.target and a.course_name like '%"+courseName+"%')");
		}
		UserPrincipalUtil.getPriceMegod(wheres, sysUsers, "createUser");
		wheres.orderBy(" create_time desc ");
		PageUtil<QuestClassHistory> page=questClassHistoryService.listPageCount(wheres);
		if(page!=null){
			List<QuestClassHistory> subjectsList=page.getData();
			if(subjectsList!=null && subjectsList.size()>0){
				for (QuestClassHistory questClassHistory : subjectsList) {
					String userId=questClassHistory.getCreateUser();
					String rcourseId=questClassHistory.getTarget();
					if(userId!=null && userId.length()>0){
						SysUser sysUser=sysUserService.get(userId);
						if(sysUser!=null){
							questClassHistory.setCreateUser(sysUser.getName());;
						}
					}
				}
			}
		}
		return super.packForBT(page);
	}
	
	@RequestMapping("toAdd")
	public String toAdd(Model model) {
		SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
		WherePrams wheres=Method.where("delFlag", C.EQ, 0);
		UserPrincipalUtil.getPriceMegod(wheres, sysUser, "userId");
		wheres.orderBy(" create_time desc");
		return "subjects/questClass/questClass_add";
	}
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	//@RequiresPermissions("quest_add")
	public Object add(QuestClass questClass, HttpServletRequest req) throws Exception {
		SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
		questClass.setCreateTime(DateUtil.dateToString(new Date(), "yyy-MM-dd HH:mm:ss"));
		questClass.setCreateUser(sysUser.getId());;
		String flag=questClassService.addLocalByid(questClass);
	    log.info("============保存成功===============");
	    return new ResultObj(0, "保存成功", flag);
	}
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	@ResponseBody
	//@RequiresPermissions("quest_delete")
	public Object delete(String id, HttpServletRequest req) throws Exception {
		if (!StringUtils.isNotEmpty(id)) {
            return new ResultObj(1, "参数传递错误", null);
        }
		QuestClass qc=questClassService.get(id);
		qc.setIsDelete(1);
		int flag=questClassService.update(qc);
	    log.info("============保存成功===============");
	    return new ResultObj(0, "保存成功", flag);
	}
	@RequestMapping("toUpdate/{id}")
	public String toUpdate(Model model,@PathVariable String id) {
		SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
		WherePrams wheres=Method.where("delFlag", C.EQ, 0);
		UserPrincipalUtil.getPriceMegod(wheres, sysUser, "userId");
		wheres.orderBy(" create_time desc");
		QuestClass questClass=questClassService.get(id);
		
		
		
		WherePrams wheres2=Method.where("isDelete", C.EQ,0 );
		wheres2.and("catagoryId",C.EQ,id);
		List<Subjects> subjectsList=subjectsService.list(wheres2);
		
		model.addAttribute("questClass", questClass);
		model.addAttribute("subjectsList", subjectsList);
		
		return "subjects/questClass/questClass_update";
	}
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	@ResponseBody
	//@RequiresPermissions("quest_update")
	public Object update(QuestClass questClass, HttpServletRequest req) throws Exception {
		int flag=questClassService.update(questClass);
		String classId=questClass.getId();
		//WherePrams sbWhere=Method.where("", c, value)
	    log.info("============保存成功===============");
	    return new ResultObj(0, "保存成功", flag);
	}
	
	
	@RequestMapping("publishById/{id}")
	@ResponseBody
	public Object publishById(@PathVariable String id) {
		
		
		String result=publish(id,new Date());
		return new ResultObj(0, "保存成功", result);
	}
	
	
	//就是往history里复制一遍持久化不再修改数据
	//date为了泛用于各种时间类型的计划
	public String publish(String id,Date date) {
		
		WherePrams wheres=Method.where("isDelete", C.EQ, 0);
		wheres.and("id", C.EQ, id);
		QuestClass questClass=questClassService.get(wheres);
		
		
		 
		QuestClassHistory  questClassHistory=new QuestClassHistory();
		
		questClassHistory.setClassName(questClass.getClassName());
		questClassHistory.setExamineTimes(questClass.getExamineTimes());
		questClassHistory.setExamineType(questClass.getExamineType());
		questClassHistory.setExpiration(questClass.getExpiration());
		questClassHistory.setMaxImgs(questClass.getMaxImgs());
		questClassHistory.setTarget(questClass.getTarget());
		questClassHistory.setDeduct(questClass.getDeduct());
		questClassHistory.setMinimalDeduct(questClass.getMinimalDeduct());
		questClassHistory.setPublishFrom(questClass.getPublishFrom());
		questClassHistory.setRemark(questClass.getRemark());
		questClassHistory.setAbarbeitung(questClass.getAbarbeitung());
		questClassHistory.setCreateTime(DateUtil.dateToString(date, "yyy-MM-dd HH:mm:ss"));
		
		String result=questClassHistoryService.addLocalByid(questClassHistory);
		
		
		WherePrams wheres2=Method.where("isDelete", C.EQ, 0);
		wheres2.and("catagoryId", C.EQ, id);
		List<Subjects> subjectsList=subjectsService.list(wheres2);
		subjectsList.forEach(tmp->{
			SubjectsHistory subjectsHistory = new SubjectsHistory();
			subjectsHistory.setSubNo(tmp.getSubNo());
			subjectsHistory.setCatagoryId(result);
			subjectsHistory.setExamClass(tmp.getExamClass());
			subjectsHistory.setContent(tmp.getContent());
			subjectsHistory.setAnswer(tmp.getAnswer());
			subjectsHistory.setHelps(tmp.getHelps());
			subjectsHistory.setRemark(tmp.getRemark());
			subjectsHistory.setSort(tmp.getSort());
			subjectsHistory.setCreateTime(DateUtil.dateToString(date, "yyy-MM-dd HH:mm:ss"));
			
			subjectsHistoryService.addLocalByid(subjectsHistory);
		});
		
		return result;
	}
}









